package com.sunwayhorizo.health.business.clinic.emr.template;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.base.BaseManager;
import com.sunwayhorizo.health.business.clinic.emr.template.query.TemplateQueryLocal;
import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.business.dto.clinic.emr.template.TemplateDTO;
import com.sunwayhorizo.health.business.dto.patad.empi.PatientBaseInfoDTO;
import com.sunwayhorizo.health.business.registries.employee.EmployeeManagerLocal;
import com.sunwayhorizo.health.common.DataTypeUtil;
import com.sunwayhorizo.health.common.DateUtil;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.datatypes.CS;
import com.sunwayhorizo.health.hl7.datatypes.ED;
import com.sunwayhorizo.health.hl7.rim.ActParticipation;
import com.sunwayhorizo.health.hl7.rim.Document;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.vocabulary.ParticipationType;
import com.sunwayhorizo.health.hl7.vocabulary.SystemBusinessConstantsCode;

/**
 * @ClassName TemplateAuditManager <br>
 * @PackageName com.sunwayhorizo.health.business.emr.template <br>
 * @Description <br>
 * @Author jinzw <br>
 * @Date 2010-03-01 <br>
 * @Version 1.0 <br>
 * @ModifiedDesc <br>
 * @ModifiedDate 2011-06-19<br>
 * @ModifiedBy jinzw<br>
 * @Copyright 2010-2020 北京三维海容 All Rights Reserved. <br>
 */
@Stateless
@Name(value = "TemplateAuditManager")
public class TemplateAuditManager extends BaseManager implements TemplateAuditManagerLocal
{
    private TemplateQueryLocal templateQuery = (TemplateQueryLocal) Component.getInstance("TemplateQuery");


    public ResultsDTO commitToAuditor(TemplateDTO tempDto) throws Hl7Exception
    {
        if (null == tempDto)
        {
            log.info("提交审核失败  tempDto: " + tempDto);
            return this.getResultsDTO("提交审核失败", false, null);
        }
        // 得到需要参与到模板审核的信息
        String actId = tempDto.getId();
        String authorRoleId = tempDto.getEmpRoleId();
        String stat = tempDto.getState();
        if (StrUtil.isNotEmpty(actId) && StrUtil.isNotEmpty(authorRoleId) && StrUtil.isNotEmpty(stat))
        {
            if (StrUtil.isNotEmpty(authorRoleId))
            {
                Document doc = baseQuery.findDocumentById(tempDto.getId());
                CS statusCode = DataTypeUtil.getCS(stat);
                // 提交审核后的审核状态
                doc.setStatusCode(statusCode);
                em.merge(doc);
                log.info("提交审核成功 actId: " + actId + " stat: " + stat);
                dto.setResultDesc("提交审核成功");
                dto.setResultFlag(true);
            }
            else
            {
                log.info("提交审核失败 actId: " + actId + " stat: " + stat + "  authorRoleId: " + authorRoleId);
                dto.setResultDesc("提交审核失败");
                dto.setResultFlag(true);
            }
        }
        else
        {
            log.info("提交审核失败  actId: " + actId + " stat: " + stat);
            dto.setResultDesc("提交审核失败");
            dto.setResultFlag(false);
        }
        return dto;
    }


    @SuppressWarnings("unchecked")
    public ResultsDTO getAuditorWorkList(TemplateDTO tempDto) throws Hl7Exception
    {
        if (null == tempDto)
        {
            log.info("获取待审核模板文件失败：tempDto: " + tempDto);
            return getResultsDTO("获取待审核模板文件失败", true, null);
        }
        // 审核人所在科室角色
        String deptRoleId = tempDto.getDeptRoleId();
        // 审核范围
        String scope = tempDto.getAuditScope();

        if (StrUtil.isNotEmpty(deptRoleId) && StrUtil.isNotEmpty(scope))
        {
            List<Object> docs = null;
            if (SystemBusinessConstantsCode.AUD_HOSPITAL.toString().equals(scope))
            {
                docs = templateQuery.findAllHospitalToAuditorTemp();
            }
            else if (SystemBusinessConstantsCode.AUD_DEPTMENT.toString().equals(scope))
            {
                List<String> wgIds = tempDto.getWorkGroupId();
                docs = templateQuery.findAllDeptAndWGToAuditorTemp(deptRoleId, wgIds);
            }
            if (ListUtil.isNotEmpty(docs))
            {
                List<TemplateDTO> result = converTemplateDTOListToList(docs);
                return getResultsDTO("获取待审核模板文件列表成功", true, result);
            }
        }
        log.info("获取待审核模板文件失败：deptRoleId: " + deptRoleId + " 审核范围 scope ： " + scope);
        return getResultsDTO("获取待审核模板文件失败 ", true, null);

    }


    @SuppressWarnings("unchecked")
    public ResultsDTO getAuditByWorkList(TemplateDTO tempDto) throws Hl7Exception
    {
        if (null == tempDto)
        {
            log.info("获取已审核模板文件失败：tempDto: " + tempDto);
            return getResultsDTO("获取已审核模板文件失败", true, null);
        }

        // 审核人所在科室角色id（全部拿科室一级的）
        String deptRoleId = tempDto.getDeptRoleId();
        String scope = tempDto.getAuditScope();

        if (StrUtil.isNotEmpty(deptRoleId) && StrUtil.isNotEmpty(scope))
        {
            List<Object> docs = null;
            if (SystemBusinessConstantsCode.AUD_HOSPITAL.toString().equals(scope))
            {
                docs = templateQuery.findAllHospitalAlreadyAuditorTemp();
            }
            else if (SystemBusinessConstantsCode.AUD_DEPTMENT.toString().equals(scope))
            {
                List<String> wgIds = tempDto.getWorkGroupId();
                docs = templateQuery.findAllDeptAndWGAlreadyAuditorTemp(deptRoleId, wgIds);
            }
            if (ListUtil.isNotEmpty(docs))
            {
                List<TemplateDTO> result = converTemplateDTOListToList(docs);
                log.info("获取已审核模板文件列表成功：deptRoleId: " + deptRoleId + " 审核范围 scope ： " + scope);
                return getResultsDTO("获取已审核模板文件列表成功", true, result);
            }
        }
        log.info("获取已审核模板文件失败：deptRoleId: " + deptRoleId + " 审核范围 scope ： " + scope);
        return getResultsDTO("获取已审核模板文件失败", true, null);

    }


    public ResultsDTO auditTemplate(TemplateDTO tempDto) throws Hl7Exception
    {
        if (null == tempDto)
        {
            log.info("审核模板文件失败：tempDto: " + tempDto);
            return this.getResultsDTO("审核模板文件失败", false, null);
        }
        // 得到参与审核的信息
        String actId = tempDto.getId();
        String auditorRoleId = tempDto.getAuditorRoleId();
        String stat = tempDto.getState();
        if (StrUtil.isNotEmpty(actId) && StrUtil.isNotEmpty(auditorRoleId) && StrUtil.isNotEmpty(auditorRoleId))
        {
            // 得到需要审核的模板
            Document doc = baseQuery.findDocumentById(tempDto.getId());
            CS statusCode = DataTypeUtil.getCS(stat);
            doc.setStatusCode(statusCode);
            // 审核角色
            Role auditorRole = baseQuery.findRoleById(Long.parseLong(auditorRoleId));
            // 动作参与，如果将来需要额外的属性就往这个里面加
            ActParticipation participation = new ActParticipation();
            participation.setTypeCode(ParticipationType.AUTHEN);
            ED ed = null;
            if (StrUtil.isNotEmpty(tempDto.getNotPassInfo()))
            {
                // 打回信息
                ed = DataTypeUtil.getED(tempDto.getNotPassInfo());
                participation.setSignatureText(ed);
            }
            // 审核时间
            participation.setCreateTime(DataTypeUtil.getTS(DateUtil.GetDateTime()));
            // 模板审核角色的参与文档动作
            doc.addParticipation(participation, auditorRole);

            em.merge(doc);
            log.info("审核模板文件成功：actId: " + actId + "  auditorRoleId: " + auditorRoleId);
            dto.setResultDesc("审核模板文件成功");
            dto.setResultFlag(true);
        }
        else
        {
            log.info("审核模板文件失败：actId: " + actId + "  auditorRoleId: " + auditorRoleId);
            dto.setResultDesc("审核模板文件失败");
            dto.setResultFlag(false);
        }

        return dto;
    }


    private List<TemplateDTO> converTemplateDTOListToList(List<Object> docs) throws Hl7Exception
    {
        List<TemplateDTO> result = new ArrayList<TemplateDTO>();
        EmployeeManagerLocal empManager = (EmployeeManagerLocal) Component.getInstance("EmployeeManager");
        TemplateManagerLocal tempateManager = (TemplateManagerLocal) Component.getInstance("TemplateManager");
        for (int i = 0; i < docs.size(); i++)
        {
            Object[] arg = (Object[]) docs.get(i);
            TemplateDTO td = new TemplateDTO();
            td.setId(arg[0].toString());
            td.setName(arg[1].toString());
            td.setState(arg[2].toString());
            td.setClassId(arg[3].toString());
            td.setCreatedBy(arg[4].toString());
            PatientBaseInfoDTO patientBaseInfo1 = empManager.findPlayEntityByRoleId(Long.parseLong(arg[4].toString()));
            if (null != patientBaseInfo1)
            {
                td.setCreateByName(patientBaseInfo1.getNatureName());
            }
            String str = arg[5].toString().substring(0, 19);
            td.setCreationDate(str);
            tempateManager.convertTemplateScopeToTempDoc(arg[0].toString(), td);
            setTemplateDTOToParticipation(arg[0].toString(), td);
            result.add(td);
        }
        return result;
    }


    private void setTemplateDTOToParticipation(String actId, TemplateDTO td) throws Hl7Exception
    {
        List<ActParticipation> parts = baseQuery.findPrtcptnsByActId(Long.valueOf(actId));
        EmployeeManagerLocal empManager = (EmployeeManagerLocal) Component.getInstance("EmployeeManager");
        for (ActParticipation pat : parts)
        {
            if (pat.getTypeCode().equals(ParticipationType.AUTHEN))
            {
                PatientBaseInfoDTO patientBaseInfoDTO = empManager.findPlayEntityByRole((Role) pat.getRoleparticipation());
                // 审核人
                td.setLastUpdateBy(patientBaseInfoDTO.getNatureName());
                if (null != pat.getCreateTime())
                {
                    // 审核时间
                    td.setLastUpdateDate(pat.getCreateTime().toDateString("yyyy-MM-dd HH:mm:ss"));
                }
                break;
            }
        }
    }

}
